class_name WaterSpring
extends Node2D

var index: int = 0

var velocity: float = 0
var force: float = 0
var height: float = 0
var target_height: float = 0

signal splash
var splash_factor: float = 0.8

@onready var collision_shape_2d: CollisionShape2D = $CollisionArea/CollisionShape2D


func move(spring_constant: float, dampening: float, delta: float):
	height = position.y
	var height_dist = height - target_height
	
	var loss = -dampening * velocity
	force = - spring_constant * height_dist + loss
	
	velocity += force * delta
	position.y += velocity * delta


func set_collision_width(width: float):
	var shape = collision_shape_2d.shape as RectangleShape2D
	shape.size.x = width


func _on_collision_area_body_entered(body: Node2D) -> void:
	var speed = 0
	
	if body is RigidBody2D:
		var rigidbody = body as RigidBody2D
		speed = rigidbody.linear_velocity.y * splash_factor
	if body is CharacterBody2D:
		var characterbody = body as CharacterBody2D
		speed = characterbody.velocity.y * splash_factor
	
	splash.emit(index, speed)
	

func get_random_collision_position():
	var shape = collision_shape_2d.shape as RectangleShape2D
	var rand_x_offset = randf_range(-shape.size.x / 2.0, shape.size.x / 2.0)
	var rand_y_offset = randf_range(-shape.size.y / 2.0, shape.size.y / 2.0)
	var offset = Vector2(rand_x_offset, rand_y_offset)
	
	var target_position = collision_shape_2d.global_position + offset
	return target_position
	
